import {takeEvery} from 'redux-saga';
import {call, cancelled, fork, put, take, cancel} from 'redux-saga/effects'
import UserService from '@services/UserService';
import LogService from '@services/LogService';
import * as types from '../ActionType';

function* authorize(user, password) {
  try {
    const token = yield call(UserService.login, user, password);
    yield put({type: types.LOGIN_SUCCESS, token});
    return token;
  } catch (error) {
    yield put({type: types.LOGIN_ERROR, error})
  } finally {
    if (yield cancelled()) {
      // ... put special cancellation handling code here
    }
  }
}

function* loginFlow(action) {
  while (true) {
    const {payload: {user, pass}} = yield take(types.LOGIN);
    // fork return a Task object
    const task = yield fork(authorize, user, pass);
    const action = yield take([types.LOGOUT, types.LOGIN_ERROR]);
    if (action.type === types.LOGOUT)
      yield cancel(task);
    yield put({type: types.LOGOUT_SUCESS});
  }
}



export default function* appSaga() {
  yield fork(loginFlow);
}